﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

using Bricks.Component.Utils;
using Bricks.Business.Models;
using Bricks.Business.Models.FlowProcess;
using Bricks.Site.Models;
using Bricks.Business.Data.Repositories.ScheduleManagement;
using System.Xml;
using Bricks.Business.Service;
using Bricks.Business.Models.ScheduleManagement;
using Bricks.Component.Data;
using Bricks.Site.Models.DBViewModel.Contract;
using Bricks.Business.Data.Repositories.ProjectContract;
using Bricks.Business.Models.ProjectContract;
using System.Data;


namespace ChiDao.Business.Service.Impl
{
    [Export(typeof(IStageScheduleService))]
    internal class StageScheduleService : IStageScheduleService
    {
        #region 属性
        [Import]
        protected IStatisticsItemMaintenanceRepository StatisticsItemMaintenanceRepository { get; set; }
        [Import]
        protected ITotalReviseRepository TotalReviseRepository { get; set; }
        [Import]
        protected ITotalReviseDetailsRepository TotalReviseDetailsRepository { get; set; }
        [Import]
        protected IYearPlanReviseRepository YearPlanReviseRepository { get; set; }
        [Import]
        protected IYearPlanReviseDetailsRepository YearPlanReviseDetailsRepository { get; set; }
        [Import]
        protected IMonthPlanRepository MonthPlanRepository { get; set; }
        [Import]
        protected IMonthPlanDetailsRepository MonthPlanDetailsRepository { get; set; }
        [Import]
        protected IStageScheduleRepository StageScheduleRepository { get; set; }
        [Import]
        protected IStageScheduleDetailsRepository StageScheduleDetailsRepository { get; set; }
        [Import]
        protected IProjectInfoRepository ProjectInfoRepository { get; set; }
        #endregion

        public class TempModel
        {
            //统计项ID
            public Guid StatisticsItemID { get; set; }

            //实际完成工程量:可用于本月计划、以及开工累计
            public string EngineeringNum { get; set; }

            //实际完成金额:可用于本月计划、以及开工累计
            public string MoneyNum { get; set; }
        }

        public IQueryable<StageSchedule> StageSchedules
        {
            get { return StageScheduleRepository.Entities; }
        }

        #region 主界面加载
        public List<StageScheduleView> GetStageScheduleList(Guid projectID, string contractType, Guid contractID, string year, string month)
        {
            //获取总金额
            string totalMoney = GetTotalReviseMoney(projectID, contractType, contractID);

            //获取旬计划数据
            List<StageScheduleView> lstStageScheduleView = new List<StageScheduleView>();
            var queryData = from ssr in StageScheduleRepository.Entities
                            where ssr.ProjectID == projectID && ssr.ContractType == contractType && ssr.ContractID == contractID && ssr.Year == year && ssr.Month == month
                            //orderby ssr.StatisticalCycle descending
                            select ssr;
            foreach (var item in queryData)
            {
                StageScheduleView stageScheduleView = new StageScheduleView();
                stageScheduleView.ID = item.ID;
                stageScheduleView.FlowCode = item.FlowCode;
                stageScheduleView.ProjectID = item.ProjectID;
                stageScheduleView.ContractType = item.ContractType;
                stageScheduleView.ContractID = item.ContractID;
                stageScheduleView.Year = item.Year;
                stageScheduleView.Month = item.Month;
                stageScheduleView.StatisticalCycle = item.StatisticalCycle;
                stageScheduleView.Unit = item.Unit;
                stageScheduleView.TotalMoneyNum = totalMoney == "0" ? string.Empty : totalMoney;

                string lastYear = string.Empty;
                string lastMonth = string.Empty;
                SetLastYearAndMonth(item.Year, item.Month, ref lastYear, ref lastMonth);
                YearPlanRevise yearPlanRevise = YearPlanReviseRepository.Entities.Where(yr => yr.ProjectID == projectID && yr.ContractType == contractType && yr.ContractID == contractID && yr.StatisticalCycle == item.Year).OrderByDescending(yr => yr.ReviseDate).FirstOrDefault();
                string currentMonthPlanMoneyNum = GetLastMonthMoney(projectID, contractType, contractID, lastYear, lastMonth, yearPlanRevise, item.Month);
                stageScheduleView.CurrentMonthPlanMoneyNum = currentMonthPlanMoneyNum == "0" ? string.Empty : currentMonthPlanMoneyNum;

                stageScheduleView.StageCompletedMoneyNum = item.TotalStageCompletedMoneyNum;
                if (!string.IsNullOrEmpty(stageScheduleView.StageCompletedMoneyNum))
                {
                    if (!string.IsNullOrEmpty(stageScheduleView.CurrentMonthPlanMoneyNum))
                    {
                        stageScheduleView.StageCompletedCurrentMonthPlanProportion = Math.Round(Convert.ToDecimal(stageScheduleView.StageCompletedMoneyNum) * 100 / Convert.ToDecimal(currentMonthPlanMoneyNum), 1).ToString() + "%";
                    }
                }

                decimal constructionCompletedMoneyNum = 0;
                GetCumulativeCompletedMoney(projectID, contractType, contractID, item.Year, item.Month, item.StatisticalCycleNum, ref constructionCompletedMoneyNum);
                stageScheduleView.ConstructionCompletedMoneyNum = constructionCompletedMoneyNum == 0 ? string.Empty : constructionCompletedMoneyNum.ToString();
                if (!string.IsNullOrEmpty(stageScheduleView.ConstructionCompletedMoneyNum))
                {
                    if (!string.IsNullOrEmpty(stageScheduleView.TotalMoneyNum))
                    {
                        stageScheduleView.ConstructionCompletedTotalProportion = Math.Round(Convert.ToDecimal(stageScheduleView.ConstructionCompletedMoneyNum) * 100 / Convert.ToDecimal(totalMoney), 1).ToString() + "%";
                    }
                }

                lstStageScheduleView.Add(stageScheduleView);
            }
            return lstStageScheduleView;
        }

        public List<StageScheduleDetailsView> GetStageScheduleDetailList(Guid projectID, string contractType, Guid contractID, string year, string month, Guid stageScheduleID)
        {
            List<StageScheduleDetailsView> lstStageScheduleDetailsView = new List<StageScheduleDetailsView>();
            StageSchedule stageSchedule = StageScheduleRepository.Entities.SingleOrDefault(ss => ss.ID == stageScheduleID);
            if (stageSchedule != null)
            {
                //获取总量维护修订明细
                Guid reviseID = GuidHelper.NewGuid();
                TotalRevise totalRevise = TotalReviseRepository.Entities.Where(t => t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID).OrderByDescending(t => t.ReviseDate).FirstOrDefault();
                if (totalRevise != null)
                {
                    reviseID = totalRevise.ID;
                }
                var queryTotalReviseDetails = from tr in TotalReviseDetailsRepository.Entities
                                              where tr.TotalReviseID == reviseID
                                              select tr;

                //设置当前年月的上一个月,获取上月计划明细
                string lastYear = string.Empty;
                string lastMonth = string.Empty;
                SetLastYearAndMonth(year, month, ref lastYear, ref lastMonth);
                List<TempModel> lstLastMonthDetail = GetLastMonthDetails(projectID, contractType, contractID, lastYear, lastMonth, year, month);


                //获取旬计划明细
                var queryStageScheduleDetails = from ssd in StageScheduleDetailsRepository.Entities
                                                where ssd.StageScheduleID == stageScheduleID
                                                select ssd;

                //获取开工累计
                List<TempModel> lstConstructionCompleted = new List<TempModel>();
                GetCumulativeCompletedDetails(projectID, contractType, contractID, year, month, stageSchedule.StatisticalCycleNum, lstConstructionCompleted);

                //获取连接查询数据
                var queryData = from s in StatisticsItemMaintenanceRepository.Entities.ToList()
                                join td in queryTotalReviseDetails
                                on s.ID equals td.StatisticsItemID into joinedEmpTD
                                from tempTD in joinedEmpTD.DefaultIfEmpty()

                                join lmd in lstLastMonthDetail
                                on s.ID equals lmd.StatisticsItemID into joinedEmpLMD
                                from tempLMD in joinedEmpLMD.DefaultIfEmpty()

                                join md in queryStageScheduleDetails
                                on s.ID equals md.StatisticsItemID into joinedEmpMD
                                from tempMD in joinedEmpMD.DefaultIfEmpty()

                                join cc in lstConstructionCompleted
                                on s.ID equals cc.StatisticsItemID into joinedEmpCC
                                from tempCC in joinedEmpCC.DefaultIfEmpty()

                                where s.IsParent == false && s.ProjectID == projectID && s.ContractType == contractType
                                orderby s.OrderNo
                                select new
                                {
                                    StatisticsItemID = s.ID,
                                    s.StatisticsItemName,
                                    s.PID,
                                    s.EngineeringUnit,
                                    s.MoneyUnit,
                                    EngineeringNum = tempTD == null ? string.Empty : tempTD.EngineeringNum,
                                    MoneyNum = tempTD == null ? string.Empty : tempTD.MoneyNum,
                                    CurrentMonthPlanEngineeringNum = tempLMD == null ? string.Empty : tempLMD.EngineeringNum,
                                    CurrentMonthPlanMoneyNum = tempLMD == null ? string.Empty : tempLMD.MoneyNum,
                                    ID = tempMD == null ? GuidHelper.NewGuid() : tempMD.ID,
                                    StageCompletedEngineeringNum = tempMD == null ? string.Empty : tempMD.StageCompletedEngineeringNum,
                                    StageCompletedMoneyNum = tempMD == null ? string.Empty : tempMD.StageCompletedMoneyNum,
                                    ConstructionCompletedEngineeringNum = tempCC == null ? string.Empty : tempCC.EngineeringNum,
                                    ConstructionCompletedMoneyNum = tempCC == null ? string.Empty : tempCC.MoneyNum
                                };

                foreach (var item in queryData)
                {
                    string parentStatisticsItemName = item.StatisticsItemName;
                    if (item.PID != null)
                    {
                        parentStatisticsItemName = GetParentStatisticsItemName(item.PID);
                    }

                    if (!string.IsNullOrEmpty(item.EngineeringUnit))
                    {
                        StageScheduleDetailsView stageScheduleDetailsView = new StageScheduleDetailsView();
                        stageScheduleDetailsView.ID = item.ID;
                        stageScheduleDetailsView.StatisticsItemID = item.StatisticsItemID;
                        stageScheduleDetailsView.StatisticsItemName = item.StatisticsItemName;
                        stageScheduleDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                        stageScheduleDetailsView.Unit = item.EngineeringUnit;
                        stageScheduleDetailsView.TotalAmount = item.EngineeringNum;
                        stageScheduleDetailsView.CurrentMonthPlanAmount = item.CurrentMonthPlanEngineeringNum;

                        stageScheduleDetailsView.StageCompletedAmount = item.StageCompletedEngineeringNum;
                        if (!string.IsNullOrEmpty(item.StageCompletedEngineeringNum) && !string.IsNullOrEmpty(item.CurrentMonthPlanEngineeringNum))
                        {
                            stageScheduleDetailsView.StageCompletedCurrentMonthPlanProportion = CountProportion(item.StageCompletedEngineeringNum, item.CurrentMonthPlanEngineeringNum);
                        }

                        stageScheduleDetailsView.ConstructionCompletedAmount = item.ConstructionCompletedEngineeringNum;
                        if (!string.IsNullOrEmpty(item.ConstructionCompletedEngineeringNum) && !string.IsNullOrEmpty(item.EngineeringNum))
                        {
                            stageScheduleDetailsView.ConstructionCompletedTotalProportion = CountProportion(item.ConstructionCompletedEngineeringNum, item.EngineeringNum);
                        }

                        lstStageScheduleDetailsView.Add(stageScheduleDetailsView);
                    }

                    if (!string.IsNullOrEmpty(item.MoneyUnit))
                    {
                        StageScheduleDetailsView stageScheduleDetailsView = new StageScheduleDetailsView();
                        stageScheduleDetailsView.ID = item.ID;
                        stageScheduleDetailsView.StatisticsItemID = item.StatisticsItemID;
                        stageScheduleDetailsView.StatisticsItemName = item.StatisticsItemName;
                        stageScheduleDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                        stageScheduleDetailsView.Unit = item.EngineeringUnit;
                        stageScheduleDetailsView.TotalAmount = item.MoneyNum;
                        stageScheduleDetailsView.CurrentMonthPlanAmount = item.CurrentMonthPlanMoneyNum;

                        stageScheduleDetailsView.StageCompletedAmount = item.StageCompletedMoneyNum;
                        if (!string.IsNullOrEmpty(item.StageCompletedMoneyNum) && !string.IsNullOrEmpty(item.CurrentMonthPlanMoneyNum))
                        {
                            stageScheduleDetailsView.StageCompletedCurrentMonthPlanProportion = CountProportion(item.StageCompletedMoneyNum, item.CurrentMonthPlanMoneyNum);
                        }

                        stageScheduleDetailsView.ConstructionCompletedAmount = item.ConstructionCompletedMoneyNum;
                        if (!string.IsNullOrEmpty(item.ConstructionCompletedMoneyNum) && !string.IsNullOrEmpty(item.MoneyNum))
                        {
                            stageScheduleDetailsView.ConstructionCompletedTotalProportion = CountProportion(item.ConstructionCompletedMoneyNum, item.MoneyNum);
                        }

                        lstStageScheduleDetailsView.Add(stageScheduleDetailsView);
                    }
                }
            }
            return lstStageScheduleDetailsView;
        }

        public List<StageScheduleView> GetStageScheduleListForPreview(Guid projectID, string contractType, List<Guid> lstContractID, string year, string month)
        {
            #region 获取总金额
            decimal totalMoney = 0;
            foreach (Guid contractID in lstContractID)
            {
                string totalMoneyStr = GetTotalReviseMoney(projectID, contractType, contractID);
                if (!string.IsNullOrEmpty(totalMoneyStr))
                {
                    totalMoney += Convert.ToDecimal(totalMoneyStr);
                }
            }
            #endregion

            //获取所有的旬计划数据
            var lstStageSchedule = from ss in StageScheduleRepository.Entities
                                   where ss.ProjectID == projectID && ss.ContractType == contractType && lstContractID.Contains(ss.ContractID) && ss.Year == year && ss.Month == month && ss.HandleState == "2"
                                   select ss;

            #region 构造旬计划初步数据
            List<StageScheduleView> lstStageScheduleView = new List<StageScheduleView>();
            foreach (StageSchedule stageSchedule in lstStageSchedule)
            {
                StageScheduleView stageScheduleView = lstStageScheduleView.SingleOrDefault(mp => mp.StatisticalCycle == stageSchedule.StatisticalCycle);
                if (stageScheduleView != null)
                {
                    //设置当月计划
                    string lastYear = string.Empty;
                    string lastMonth = string.Empty;
                    SetLastYearAndMonth(stageSchedule.Year, stageSchedule.Month, ref lastYear, ref lastMonth);
                    YearPlanRevise yearPlanRevise = YearPlanReviseRepository.Entities.Where(yr => yr.ProjectID == projectID && yr.ContractType == contractType && yr.ContractID == stageSchedule.ContractID && yr.StatisticalCycle == stageSchedule.Year).OrderByDescending(yr => yr.ReviseDate).FirstOrDefault();
                    string currentMonthPlanMoneyNum = GetLastMonthMoney(projectID, contractType, stageSchedule.ContractID, lastYear, lastMonth, yearPlanRevise, stageSchedule.Month);
                    if (currentMonthPlanMoneyNum != "0")
                    {
                        stageScheduleView.CurrentMonthPlanMoneyNum = (Convert.ToDecimal(stageScheduleView.CurrentMonthPlanMoneyNum) + Convert.ToDecimal(currentMonthPlanMoneyNum)).ToString();
                    }

                    //设置旬完成
                    if (!string.IsNullOrEmpty(stageSchedule.TotalStageCompletedMoneyNum as string))
                    {
                        stageScheduleView.StageCompletedMoneyNum = (Convert.ToDecimal(stageScheduleView.StageCompletedMoneyNum) + Convert.ToDecimal(stageSchedule.TotalStageCompletedMoneyNum)).ToString();
                    }

                    //设置开工累计
                    decimal constructionCompletedMoneyNum = 0;
                    GetCumulativeCompletedMoney(projectID, contractType, stageSchedule.ContractID, stageSchedule.Year, stageSchedule.Month, stageSchedule.StatisticalCycleNum, ref constructionCompletedMoneyNum);
                    stageScheduleView.ConstructionCompletedMoneyNum = (Convert.ToDecimal(stageScheduleView.ConstructionCompletedMoneyNum) + constructionCompletedMoneyNum).ToString();
                }
                else
                {
                    stageScheduleView = new StageScheduleView();
                    stageScheduleView.ID = GuidHelper.NewGuid();
                    stageScheduleView.StatisticalCycle = stageSchedule.StatisticalCycle;
                    stageScheduleView.Unit = stageSchedule.Unit;
                    stageScheduleView.TotalMoneyNum = totalMoney == 0 ? string.Empty : totalMoney.ToString();

                    //设置当月计划
                    string lastYear = string.Empty;
                    string lastMonth = string.Empty;
                    SetLastYearAndMonth(stageSchedule.Year, stageSchedule.Month, ref lastYear, ref lastMonth);
                    YearPlanRevise yearPlanRevise = YearPlanReviseRepository.Entities.Where(yr => yr.ProjectID == projectID && yr.ContractType == contractType && yr.ContractID == stageSchedule.ContractID && yr.StatisticalCycle == stageSchedule.Year).OrderByDescending(yr => yr.ReviseDate).FirstOrDefault();
                    stageScheduleView.CurrentMonthPlanMoneyNum = GetLastMonthMoney(projectID, contractType, stageSchedule.ContractID, lastYear, lastMonth, yearPlanRevise, stageSchedule.Month);

                    //设置旬完成
                    stageScheduleView.StageCompletedMoneyNum = "0";
                    if (!string.IsNullOrEmpty(stageSchedule.TotalStageCompletedMoneyNum as string))
                    {
                        stageScheduleView.StageCompletedMoneyNum = stageSchedule.TotalStageCompletedMoneyNum;
                    }

                    //设置开工累计
                    decimal constructionCompletedMoneyNum = 0;
                    GetCumulativeCompletedMoney(projectID, contractType, stageSchedule.ContractID, stageSchedule.Year, stageSchedule.Month, stageSchedule.StatisticalCycleNum, ref constructionCompletedMoneyNum);
                    stageScheduleView.ConstructionCompletedMoneyNum = constructionCompletedMoneyNum.ToString();

                    lstStageScheduleView.Add(stageScheduleView);
                }
            }
            #endregion

            //设置最后返回数据
            foreach (StageScheduleView stageScheduleView in lstStageScheduleView)
            {
                stageScheduleView.CurrentMonthPlanMoneyNum = stageScheduleView.CurrentMonthPlanMoneyNum == "0" ? string.Empty : stageScheduleView.CurrentMonthPlanMoneyNum;
                stageScheduleView.StageCompletedMoneyNum = stageScheduleView.StageCompletedMoneyNum == "0" ? string.Empty : stageScheduleView.StageCompletedMoneyNum;
                if (!string.IsNullOrEmpty(stageScheduleView.StageCompletedMoneyNum))
                {
                    if (!string.IsNullOrEmpty(stageScheduleView.CurrentMonthPlanMoneyNum))
                    {
                        stageScheduleView.StageCompletedCurrentMonthPlanProportion = Math.Round(Convert.ToDecimal(stageScheduleView.StageCompletedMoneyNum) * 100 / Convert.ToDecimal(stageScheduleView.CurrentMonthPlanMoneyNum), 1).ToString() + "%";
                    }
                }

                stageScheduleView.ConstructionCompletedMoneyNum = stageScheduleView.ConstructionCompletedMoneyNum == "0" ? string.Empty : stageScheduleView.ConstructionCompletedMoneyNum;
                if (!string.IsNullOrEmpty(stageScheduleView.ConstructionCompletedMoneyNum))
                {
                    if (!string.IsNullOrEmpty(stageScheduleView.TotalMoneyNum))
                    {
                        stageScheduleView.ConstructionCompletedTotalProportion = Math.Round(Convert.ToDecimal(stageScheduleView.ConstructionCompletedMoneyNum) * 100 / totalMoney, 1).ToString() + "%";
                    }
                }
            }

            return lstStageScheduleView;
        }

        public List<StageScheduleDetailsView> GetStageScheduleDetailListForPreview(Guid projectID, string contractType, List<Guid> lstContractID, string year, string month, string statisticalCycle)
        {
            #region 获取各个子查询数据
            List<TempModel> lstTotalReviseDetail = new List<TempModel>();
            List<TempModel> lstLastMonthDetail = new List<TempModel>();
            List<StageScheduleDetails> lstStageScheduleDetail = new List<StageScheduleDetails>();
            List<TempModel> lstConstructionCompleted = new List<TempModel>();
            foreach (Guid contractID in lstContractID)
            {
                //获取总量维护修订明细
                TotalRevise totalRevise = TotalReviseRepository.Entities.Where(t => t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID).OrderByDescending(t => t.ReviseDate).FirstOrDefault();
                if (totalRevise != null)
                {
                    List<TotalReviseDetails> lstTotalReviseDetailForOneContractID = TotalReviseDetailsRepository.Entities.Where(td => td.TotalReviseID == totalRevise.ID).ToList();
                    TotalTempModelForTotalReviseDetail(lstTotalReviseDetailForOneContractID, lstTotalReviseDetail);
                }

                //设置当前年月的上一个月,获取上月计划明细
                string lastYear = string.Empty;
                string lastMonth = string.Empty;
                SetLastYearAndMonth(year, month, ref lastYear, ref lastMonth);
                List<TempModel> lstLastMonthDetailForOneContractID = GetLastMonthDetails(projectID, contractType, contractID, lastYear, lastMonth, year, month);
                TotalTempModel(lstLastMonthDetailForOneContractID, lstLastMonthDetail);

                //获取旬计划明细
                IQueryable<StageScheduleDetails> lstStageScheduleDetailForOneContractID = from ss in StageScheduleRepository.Entities
                                                                                          join ssd in StageScheduleDetailsRepository.Entities
                                                                                  on ss.ID equals ssd.StageScheduleID
                                                                                          where ss.ProjectID == projectID && ss.ContractType == contractType && ss.ContractID == contractID && ss.Year == year && ss.Month == month && ss.StatisticalCycle == statisticalCycle && ss.HandleState == "2"
                                                                                          select ssd;
                TotalTempModelForStageScheduleDetail(lstStageScheduleDetailForOneContractID, lstStageScheduleDetail);

                //获取开工累计
                List<TempModel> lstConstructionCompletedForOneContractID = new List<TempModel>();
                GetCumulativeCompletedDetails(projectID, contractType, contractID, year, month, SetStatisticalCycleNum(statisticalCycle), lstConstructionCompletedForOneContractID);
                TotalTempModel(lstConstructionCompletedForOneContractID, lstConstructionCompleted);
            }
            #endregion

            //获取连接查询数据
            var queryData = from s in StatisticsItemMaintenanceRepository.Entities.ToList()
                            join td in lstTotalReviseDetail
                            on s.ID equals td.StatisticsItemID into joinedEmpTD
                            from tempTD in joinedEmpTD.DefaultIfEmpty()

                            join lmd in lstLastMonthDetail
                            on s.ID equals lmd.StatisticsItemID into joinedEmpLMD
                            from tempLMD in joinedEmpLMD.DefaultIfEmpty()

                            join md in lstStageScheduleDetail
                            on s.ID equals md.StatisticsItemID into joinedEmpMD
                            from tempMD in joinedEmpMD.DefaultIfEmpty()

                            join cc in lstConstructionCompleted
                            on s.ID equals cc.StatisticsItemID into joinedEmpCC
                            from tempCC in joinedEmpCC.DefaultIfEmpty()

                            where s.IsParent == false && s.ProjectID == projectID && s.ContractType == contractType
                            orderby s.OrderNo
                            select new
                            {
                                StatisticsItemID = s.ID,
                                s.StatisticsItemName,
                                s.PID,
                                s.EngineeringUnit,
                                s.MoneyUnit,
                                EngineeringNum = tempTD == null ? string.Empty : tempTD.EngineeringNum,
                                MoneyNum = tempTD == null ? string.Empty : tempTD.MoneyNum,
                                CurrentMonthPlanEngineeringNum = tempLMD == null ? string.Empty : tempLMD.EngineeringNum,
                                CurrentMonthPlanMoneyNum = tempLMD == null ? string.Empty : tempLMD.MoneyNum,
                                ID = tempMD == null ? GuidHelper.NewGuid() : tempMD.ID,
                                StageCompletedEngineeringNum = tempMD == null ? string.Empty : tempMD.StageCompletedEngineeringNum,
                                StageCompletedMoneyNum = tempMD == null ? string.Empty : tempMD.StageCompletedMoneyNum,
                                ConstructionCompletedEngineeringNum = tempCC == null ? string.Empty : tempCC.EngineeringNum,
                                ConstructionCompletedMoneyNum = tempCC == null ? string.Empty : tempCC.MoneyNum
                            };

            List<StageScheduleDetailsView> lstStageScheduleDetailsView = new List<StageScheduleDetailsView>();
            foreach (var item in queryData)
            {
                string parentStatisticsItemName = item.StatisticsItemName;
                if (item.PID != null)
                {
                    parentStatisticsItemName = GetParentStatisticsItemName(item.PID);
                }

                if (!string.IsNullOrEmpty(item.EngineeringUnit))
                {
                    StageScheduleDetailsView stageScheduleDetailsView = new StageScheduleDetailsView();
                    stageScheduleDetailsView.ID = item.ID;
                    stageScheduleDetailsView.StatisticsItemID = item.StatisticsItemID;
                    stageScheduleDetailsView.StatisticsItemName = item.StatisticsItemName;
                    stageScheduleDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    stageScheduleDetailsView.Unit = item.EngineeringUnit;
                    stageScheduleDetailsView.TotalAmount = item.EngineeringNum;
                    stageScheduleDetailsView.CurrentMonthPlanAmount = item.CurrentMonthPlanEngineeringNum;

                    stageScheduleDetailsView.StageCompletedAmount = item.StageCompletedEngineeringNum;
                    if (!string.IsNullOrEmpty(item.StageCompletedEngineeringNum) && !string.IsNullOrEmpty(item.CurrentMonthPlanEngineeringNum))
                    {
                        stageScheduleDetailsView.StageCompletedCurrentMonthPlanProportion = CountProportion(item.StageCompletedEngineeringNum, item.CurrentMonthPlanEngineeringNum);
                    }

                    stageScheduleDetailsView.ConstructionCompletedAmount = item.ConstructionCompletedEngineeringNum;
                    if (!string.IsNullOrEmpty(item.ConstructionCompletedEngineeringNum) && !string.IsNullOrEmpty(item.EngineeringNum))
                    {
                        stageScheduleDetailsView.ConstructionCompletedTotalProportion = CountProportion(item.ConstructionCompletedEngineeringNum, item.EngineeringNum);
                    }

                    lstStageScheduleDetailsView.Add(stageScheduleDetailsView);
                }

                if (!string.IsNullOrEmpty(item.MoneyUnit))
                {
                    StageScheduleDetailsView stageScheduleDetailsView = new StageScheduleDetailsView();
                    stageScheduleDetailsView.ID = item.ID;
                    stageScheduleDetailsView.StatisticsItemID = item.StatisticsItemID;
                    stageScheduleDetailsView.StatisticsItemName = item.StatisticsItemName;
                    stageScheduleDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    stageScheduleDetailsView.Unit = item.EngineeringUnit;
                    stageScheduleDetailsView.TotalAmount = item.MoneyNum;
                    stageScheduleDetailsView.CurrentMonthPlanAmount = item.CurrentMonthPlanMoneyNum;

                    stageScheduleDetailsView.StageCompletedAmount = item.StageCompletedMoneyNum;
                    if (!string.IsNullOrEmpty(item.StageCompletedMoneyNum) && !string.IsNullOrEmpty(item.CurrentMonthPlanMoneyNum))
                    {
                        stageScheduleDetailsView.StageCompletedCurrentMonthPlanProportion = CountProportion(item.StageCompletedMoneyNum, item.CurrentMonthPlanMoneyNum);
                    }

                    stageScheduleDetailsView.ConstructionCompletedAmount = item.ConstructionCompletedMoneyNum;
                    if (!string.IsNullOrEmpty(item.ConstructionCompletedMoneyNum) && !string.IsNullOrEmpty(item.MoneyNum))
                    {
                        stageScheduleDetailsView.ConstructionCompletedTotalProportion = CountProportion(item.ConstructionCompletedMoneyNum, item.MoneyNum);
                    }

                    lstStageScheduleDetailsView.Add(stageScheduleDetailsView);
                }
            }
            return lstStageScheduleDetailsView;
        }
        #endregion

        #region 流程加载
        public StageScheduleView GetStageScheduleByID(Guid id)
        {
            StageSchedule stageSchedule = StageScheduleRepository.Entities.SingleOrDefault(t => t.ID == id);
            StageScheduleView stageScheduleView = null;
            if (stageSchedule != null)
            {
                stageScheduleView = new StageScheduleView();
                stageScheduleView.ID = stageSchedule.ID;
                stageScheduleView.FlowCode = stageSchedule.FlowCode;
                stageScheduleView.ProjectID = stageSchedule.ProjectID;
                stageScheduleView.ContractType = stageSchedule.ContractType;
                stageScheduleView.ContractID = stageSchedule.ContractID;
                stageScheduleView.Year = stageSchedule.Year;
                stageScheduleView.Month = stageSchedule.Month;
                stageScheduleView.StatisticalCycle = stageSchedule.StatisticalCycle;
                stageScheduleView.Unit = stageSchedule.Unit;
                stageScheduleView.TotalStageCompletedMoneyNum = stageSchedule.TotalStageCompletedMoneyNum;
                stageScheduleView.RequestDate = stageSchedule.RequestDate;
                stageScheduleView.RequestPerson = stageSchedule.RequestPerson;
                stageScheduleView.HandleState = stageSchedule.HandleState;
                stageScheduleView.AssociatedNodeCode = stageSchedule.AssociatedNodeCode;
                stageScheduleView.LastUpdateUserDepartment = stageSchedule.LastUpdateUserDepartment;
                stageScheduleView.LastUpdateUser = stageSchedule.LastUpdateUser;
                stageScheduleView.LastUpdateTime = stageSchedule.LastUpdateTime;
                stageScheduleView.SaveState = stageSchedule.SaveState;
            }
            return stageScheduleView;
        }

        public List<StageScheduleDetailsView> GetStageScheduleDetailListForFlow(Guid projectID, string contractType, Guid contractID, string year, string month, Guid stageScheduleID)
        {
            //获取总量维护修订ID
            Guid reviseID = GuidHelper.NewGuid();
            TotalRevise totalRevise = TotalReviseRepository.Entities.Where(t => t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID).OrderByDescending(t => t.ReviseDate).FirstOrDefault();
            if (totalRevise != null)
            {
                reviseID = totalRevise.ID;
            }

            //获取总量维护修订明细
            var queryTotalReviseDetails = from tr in TotalReviseDetailsRepository.Entities
                                          where tr.TotalReviseID == reviseID
                                          select tr;

            //设置当前年月的上一个月,获取上月计划明细
            string lastYear = string.Empty;
            string lastMonth = string.Empty;
            SetLastYearAndMonth(year, month, ref lastYear, ref lastMonth);
            List<TempModel> lstLastMonthDetail = GetLastMonthDetails(projectID, contractType, contractID, lastYear, lastMonth, year, month);


            //获取旬计划明细
            var queryStageScheduleDetails = from md in StageScheduleDetailsRepository.Entities
                                            where md.StageScheduleID == stageScheduleID
                                            select md;

            var queryData = from s in StatisticsItemMaintenanceRepository.Entities.ToList()
                            join td in queryTotalReviseDetails
                            on s.ID equals td.StatisticsItemID into joinedEmpTD
                            from tempTD in joinedEmpTD.DefaultIfEmpty()

                            join lmd in lstLastMonthDetail
                            on s.ID equals lmd.StatisticsItemID into joinedEmpLMD
                            from tempLMD in joinedEmpLMD.DefaultIfEmpty()

                            join md in queryStageScheduleDetails
                            on s.ID equals md.StatisticsItemID into joinedEmpMD
                            from tempMD in joinedEmpMD.DefaultIfEmpty()
                            where s.IsParent == false && s.ProjectID == projectID && s.ContractType == contractType
                            orderby s.OrderNo
                            select new
                            {
                                StatisticsItemID = s.ID,
                                s.StatisticsItemName,
                                s.PID,
                                s.EngineeringUnit,
                                s.MoneyUnit,
                                EngineeringNum = tempTD == null ? string.Empty : tempTD.EngineeringNum,
                                MoneyNum = tempTD == null ? string.Empty : tempTD.MoneyNum,
                                StageScheduleID = stageScheduleID,
                                CurrentMonthPlanEngineeringNum = tempLMD == null ? string.Empty : tempLMD.EngineeringNum,
                                CurrentMonthPlanMoneyNum = tempLMD == null ? string.Empty : tempLMD.MoneyNum,
                                ID = tempMD == null ? GuidHelper.NewGuid() : tempMD.ID,
                                StageCompletedEngineeringNum = tempMD == null ? string.Empty : tempMD.StageCompletedEngineeringNum,
                                StageCompletedMoneyNum = tempMD == null ? string.Empty : tempMD.StageCompletedMoneyNum
                            };

            List<StageScheduleDetailsView> lstStageScheduleDetailsView = new List<StageScheduleDetailsView>();
            foreach (var item in queryData)
            {
                string parentStatisticsItemName = item.StatisticsItemName;
                if (item.PID != null)
                {
                    parentStatisticsItemName = GetParentStatisticsItemName(item.PID);
                }

                if (!string.IsNullOrEmpty(item.EngineeringUnit))
                {
                    StageScheduleDetailsView stageScheduleDetailsView = new StageScheduleDetailsView();
                    stageScheduleDetailsView.ID = item.ID;
                    stageScheduleDetailsView.StageScheduleID = item.StageScheduleID;
                    stageScheduleDetailsView.StatisticsItemID = item.StatisticsItemID;
                    stageScheduleDetailsView.StatisticsItemName = item.StatisticsItemName;
                    stageScheduleDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    stageScheduleDetailsView.Unit = item.EngineeringUnit;
                    stageScheduleDetailsView.TotalAmount = item.EngineeringNum;
                    stageScheduleDetailsView.CurrentMonthPlanAmount = item.CurrentMonthPlanEngineeringNum;
                    stageScheduleDetailsView.StageCompletedAmount = item.StageCompletedEngineeringNum;
                    stageScheduleDetailsView.IsBelongToMoneyNum = "0";
                    lstStageScheduleDetailsView.Add(stageScheduleDetailsView);
                }

                if (!string.IsNullOrEmpty(item.MoneyUnit))
                {
                    StageScheduleDetailsView stageScheduleDetailsView = new StageScheduleDetailsView();
                    stageScheduleDetailsView.ID = item.ID;
                    stageScheduleDetailsView.StageScheduleID = item.StageScheduleID;
                    stageScheduleDetailsView.StatisticsItemID = item.StatisticsItemID;
                    stageScheduleDetailsView.StatisticsItemName = item.StatisticsItemName;
                    stageScheduleDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    stageScheduleDetailsView.Unit = item.MoneyUnit;
                    stageScheduleDetailsView.TotalAmount = item.MoneyNum;
                    stageScheduleDetailsView.CurrentMonthPlanAmount = item.CurrentMonthPlanMoneyNum;
                    stageScheduleDetailsView.StageCompletedAmount = item.StageCompletedMoneyNum;
                    stageScheduleDetailsView.IsBelongToMoneyNum = "1";
                    lstStageScheduleDetailsView.Add(stageScheduleDetailsView);
                }
            }
            return lstStageScheduleDetailsView;
        }
        #endregion

        #region 加载私有函数
        //获取指定项目、合同类型和标段下总量维护最后修订金额
        private string GetTotalReviseMoney(Guid projectID, string contractType, Guid contractID)
        {
            string totalMoney = string.Empty;
            TotalRevise totalRevise = TotalReviseRepository.Entities.Where(t => t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID).OrderByDescending(t => t.ReviseDate).FirstOrDefault();
            if (totalRevise != null)
            {
                totalMoney = totalRevise.ReviseMoney;
            }
            return totalMoney;
        }

        //设置当前年月的上一个月
        private void SetLastYearAndMonth(string year, string month, ref string lastYear, ref string lastMonth)
        {
            if (!string.IsNullOrEmpty(year) && !string.IsNullOrEmpty(month))
            {
                lastYear = year;
                int monthNum = Convert.ToInt32(month);
                if (monthNum == 1)
                {
                    lastYear = (Convert.ToInt32(year) - 1).ToString();
                    lastMonth = "12";
                }
                else
                {
                    lastMonth = (monthNum - 1).ToString();
                }
            }
        }

        //获取月进度计划中上月月度计划审批完成的下月计划金额，为审批结束的取年计划中对应月计划数据
        private string GetLastMonthMoney(Guid projectID, string contractType, Guid contractID, string lastYear, string lastMonth, YearPlanRevise yearPlanRevise, string month)
        {
            string lastMonthMoney = "0";
            MonthPlan monthPlan = MonthPlanRepository.Entities.SingleOrDefault(m => m.ProjectID == projectID && m.ContractType == contractType && m.ContractID == contractID && m.Year == lastYear && m.Month == lastMonth);
            if (monthPlan != null && monthPlan.HandleState == "2")
            {
                lastMonthMoney = monthPlan.TotalNextMonthPlanMoneyNum;
            }
            else
            {
                if (yearPlanRevise != null)
                {
                    switch (month)
                    {
                        case "1":
                            lastMonthMoney = yearPlanRevise.JanuaryMoneyNum;
                            break;
                        case "2":
                            lastMonthMoney = yearPlanRevise.FebruaryMoneyNum;
                            break;
                        case "3":
                            lastMonthMoney = yearPlanRevise.MarchMoneyNum;
                            break;
                        case "4":
                            lastMonthMoney = yearPlanRevise.AprilMoneyNum;
                            break;
                        case "5":
                            lastMonthMoney = yearPlanRevise.MayMoneyNum;
                            break;
                        case "6":
                            lastMonthMoney = yearPlanRevise.JuneMoneyNum;
                            break;
                        case "7":
                            lastMonthMoney = yearPlanRevise.JulyMoneyNum;
                            break;
                        case "8":
                            lastMonthMoney = yearPlanRevise.AugustMoneyNum;
                            break;
                        case "9":
                            lastMonthMoney = yearPlanRevise.SeptemberMoneyNum;
                            break;
                        case "10":
                            lastMonthMoney = yearPlanRevise.OctoberMoneyNum;
                            break;
                        case "11":
                            lastMonthMoney = yearPlanRevise.NovemberMoneyNum;
                            break;
                        case "12":
                            lastMonthMoney = yearPlanRevise.DecemberMoneyNum;
                            break;
                    }
                }
            }
            return lastMonthMoney;
        }

        //获取开工累计完成金额
        private void GetCumulativeCompletedMoney(Guid projectID, string contractType, Guid contractID, string year, string month, string statisticalCycleNum, ref decimal constructionCompletedMoneyNum)
        {
            int yearNum = Convert.ToInt32(year);
            IQueryable<StageSchedule> lstStageSchedule = StageScheduleRepository.Entities.Where(m => m.ProjectID == projectID && m.ContractType == contractType && m.ContractID == contractID && ((m.Year.CompareTo(year) < 0) || (m.Year == year && m.Month.CompareTo(month) < 0) || (m.Year == year && m.Month == month && m.StatisticalCycleNum.CompareTo(statisticalCycleNum) <= 0)) && m.HandleState == "2");
            foreach (StageSchedule stageSchedule in lstStageSchedule)
            {
                if (!string.IsNullOrEmpty(stageSchedule.TotalStageCompletedMoneyNum))
                {
                    constructionCompletedMoneyNum = constructionCompletedMoneyNum + Convert.ToDecimal(stageSchedule.TotalStageCompletedMoneyNum);
                }
            }
        }

        //获取开工累计完成金额明细
        private void GetCumulativeCompletedDetails(Guid projectID, string contractType, Guid contractID, string year, string month, string statisticalCycleNum, List<TempModel> lstConstructionCompleted)
        {
            int yearNum = Convert.ToInt32(year);
            IQueryable<StageSchedule> lstStageSchedule = StageScheduleRepository.Entities.Where(m => m.ProjectID == projectID && m.ContractType == contractType && m.ContractID == contractID && ((m.Year.CompareTo(year) < 0) || (m.Year == year && m.Month.CompareTo(month) < 0) || (m.Year == year && m.Month == month && m.StatisticalCycleNum.CompareTo(statisticalCycleNum) <= 0)) && m.HandleState == "2");
            foreach (StageSchedule stageSchedule in lstStageSchedule)
            {
                //获取旬计划明细
                IQueryable<StageScheduleDetails> lstStageScheduleDetail = StageScheduleDetailsRepository.Entities.Where(md => md.StageScheduleID == stageSchedule.ID);
                foreach (StageScheduleDetails stageScheduleDetails in lstStageScheduleDetail)
                {
                    StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.Single(s => s.ID == stageScheduleDetails.StatisticsItemID);
                    if (statisticsItemMaintenance != null)
                    {
                        TempModel exists = lstConstructionCompleted.SingleOrDefault(t => t.StatisticsItemID == stageScheduleDetails.StatisticsItemID);
                        if (exists == null)
                        {
                            lstConstructionCompleted.Add(new TempModel()
                            {
                                StatisticsItemID = stageScheduleDetails.StatisticsItemID,
                                EngineeringNum = stageScheduleDetails.StageCompletedEngineeringNum,
                                MoneyNum = stageScheduleDetails.StageCompletedMoneyNum
                            });
                        }
                        else
                        {
                            exists.EngineeringNum = CountEngineeringOrMoneyNumForDetails(stageScheduleDetails.StageCompletedEngineeringNum, exists.EngineeringNum);
                            exists.MoneyNum = CountEngineeringOrMoneyNumForDetails(stageScheduleDetails.StageCompletedMoneyNum, exists.MoneyNum);
                        }
                    }
                }
            }
        }

        //统计工程量或者金额
        private string CountEngineeringOrMoneyNumForDetails(string engineeringOrMoneyNum, string totalEngineeringOrMoneyNum)
        {
            if (!string.IsNullOrEmpty(engineeringOrMoneyNum))
            {
                if (string.IsNullOrEmpty(totalEngineeringOrMoneyNum))
                {
                    totalEngineeringOrMoneyNum = engineeringOrMoneyNum;
                }
                else
                {
                    if (totalEngineeringOrMoneyNum.Contains('/'))
                    {
                        string[] totalEngineeringOrMoneyNumArr = totalEngineeringOrMoneyNum.Split('/');
                        string[] engineeringOrMoneyNumArr = engineeringOrMoneyNum.Split('/');
                        if (engineeringOrMoneyNumArr.Length == 2)
                        {
                            totalEngineeringOrMoneyNum = (Convert.ToDecimal(totalEngineeringOrMoneyNumArr[0]) + Convert.ToDecimal(engineeringOrMoneyNumArr[0])).ToString() + "/" + (Convert.ToDecimal(totalEngineeringOrMoneyNumArr[1]) + Convert.ToDecimal(engineeringOrMoneyNumArr[1])).ToString();
                        }
                        else if (engineeringOrMoneyNumArr.Length == 1)
                        {
                            totalEngineeringOrMoneyNum = (Convert.ToDecimal(totalEngineeringOrMoneyNumArr[0]) + Convert.ToDecimal(engineeringOrMoneyNumArr[0])).ToString() + "/" + totalEngineeringOrMoneyNumArr[1];
                        }
                    }
                    else
                    {
                        string[] engineeringOrMoneyNumArr = engineeringOrMoneyNum.Split('/');
                        if (engineeringOrMoneyNumArr.Length == 1)
                        {
                            totalEngineeringOrMoneyNum = (Convert.ToDecimal(totalEngineeringOrMoneyNum) + Convert.ToDecimal(engineeringOrMoneyNum)).ToString();
                        }
                        else if (engineeringOrMoneyNumArr.Length == 2)
                        {
                            totalEngineeringOrMoneyNum = (Convert.ToDecimal(totalEngineeringOrMoneyNum) + Convert.ToDecimal(engineeringOrMoneyNumArr[0])).ToString() + "/" + engineeringOrMoneyNumArr[1];
                        }
                    }
                }
            }
            return totalEngineeringOrMoneyNum;
        }

        //计算百分比
        private string CountProportion(string num, string totalNum, int digit = 1)
        {
            string proportion = string.Empty;
            if (!string.IsNullOrEmpty(totalNum))
            {
                string totalNumTemp = totalNum;
                if (totalNum.Contains('/'))
                {
                    totalNumTemp = totalNum.Split('/')[0];
                }
                string numTemp = num;
                if (num.Contains('/'))
                {
                    numTemp = num.Split('/')[0];
                }
                if (!string.IsNullOrEmpty(totalNumTemp) && totalNumTemp != "0" && !string.IsNullOrEmpty(numTemp) && numTemp != "0")
                {
                    proportion = Math.Round(Convert.ToDecimal(numTemp) * 100 / Convert.ToDecimal(totalNumTemp), digit).ToString() + "%";
                }
            }
            return proportion;
        }

        //统计总量维护各个标段修订明细列表
        private void TotalTempModelForTotalReviseDetail(List<TotalReviseDetails> lstTotalReviseDetailForOneContract, List<TempModel> lstTotalReviseDetail)
        {
            foreach (TotalReviseDetails totalReviseDetails in lstTotalReviseDetailForOneContract)
            {
                StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.Single(s => s.ID == totalReviseDetails.StatisticsItemID);
                if (statisticsItemMaintenance != null)
                {
                    TempModel exists = lstTotalReviseDetail.SingleOrDefault(t => t.StatisticsItemID == totalReviseDetails.StatisticsItemID);
                    if (exists == null)
                    {
                        lstTotalReviseDetail.Add(new TempModel()
                        {
                            StatisticsItemID = totalReviseDetails.StatisticsItemID,
                            EngineeringNum = totalReviseDetails.EngineeringNum,
                            MoneyNum = totalReviseDetails.MoneyNum
                        });
                    }
                    else
                    {
                        exists.EngineeringNum = CountEngineeringOrMoneyNumForDetails(totalReviseDetails.EngineeringNum, exists.EngineeringNum);
                        exists.MoneyNum = CountEngineeringOrMoneyNumForDetails(totalReviseDetails.MoneyNum, exists.MoneyNum);
                    }
                }
            }
        }


        //统计上月计划、本年或者开工累计各个标段修订明细列表
        private void TotalTempModel(List<TempModel> lstDetailForOneContract, List<TempModel> lstDetail)
        {
            foreach (TempModel tempModel in lstDetailForOneContract)
            {
                StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.Single(s => s.ID == tempModel.StatisticsItemID);
                if (statisticsItemMaintenance != null)
                {
                    TempModel exists = lstDetail.SingleOrDefault(t => t.StatisticsItemID == tempModel.StatisticsItemID);
                    if (exists == null)
                    {
                        lstDetail.Add(new TempModel()
                        {
                            StatisticsItemID = tempModel.StatisticsItemID,
                            EngineeringNum = tempModel.EngineeringNum,
                            MoneyNum = tempModel.MoneyNum
                        });
                    }
                    else
                    {
                        exists.EngineeringNum = CountEngineeringOrMoneyNumForDetails(tempModel.EngineeringNum, exists.EngineeringNum);
                        exists.MoneyNum = CountEngineeringOrMoneyNumForDetails(tempModel.MoneyNum, exists.MoneyNum);
                    }
                }
            }
        }

        //统计旬计划各个标段修订明细列表
        private void TotalTempModelForStageScheduleDetail(IQueryable<StageScheduleDetails> lstStageScheduleDetailForOneContract, List<StageScheduleDetails> lstStageScheduleDetail)
        {
            foreach (StageScheduleDetails stageScheduleDetails in lstStageScheduleDetailForOneContract)
            {
                StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.Single(s => s.ID == stageScheduleDetails.StatisticsItemID);
                if (statisticsItemMaintenance != null)
                {
                    StageScheduleDetails exists = lstStageScheduleDetail.SingleOrDefault(t => t.StatisticsItemID == stageScheduleDetails.StatisticsItemID);
                    if (exists == null)
                    {
                        lstStageScheduleDetail.Add(stageScheduleDetails.CopyTo<StageScheduleDetails>());
                    }
                    else
                    {
                        exists.StageCompletedEngineeringNum = CountEngineeringOrMoneyNumForDetails(stageScheduleDetails.StageCompletedEngineeringNum, exists.StageCompletedEngineeringNum);
                        exists.StageCompletedMoneyNum = CountEngineeringOrMoneyNumForDetails(stageScheduleDetails.StageCompletedMoneyNum, exists.StageCompletedMoneyNum);
                    }
                }
            }
        }

        //获取月进度计划中上月月度计划审批完成的下月计划金额明细，为审批结束的取年计划中对应月计划数据明细
        private List<TempModel> GetLastMonthDetails(Guid projectID, string contractType, Guid contractID, string lastYear, string lastMonth, string year, string month)
        {
            List<TempModel> lstLastMonthDetail = new List<TempModel>();
            MonthPlan monthPlan = MonthPlanRepository.Entities.SingleOrDefault(m => m.ProjectID == projectID && m.ContractType == contractType && m.ContractID == contractID && m.Year == lastYear && m.Month == lastMonth);
            if (monthPlan != null && monthPlan.HandleState == "2")
            {
                IQueryable<MonthPlanDetails> lstMonthPlanDetail = MonthPlanDetailsRepository.Entities.Where(md => md.MonthPlanID == monthPlan.ID);
                foreach (MonthPlanDetails monthPlanDetails in lstMonthPlanDetail)
                {
                    lstLastMonthDetail.Add(new TempModel()
                    {
                        StatisticsItemID = monthPlanDetails.StatisticsItemID,
                        EngineeringNum = monthPlanDetails.NextMonthPlanEngineeringNum,
                        MoneyNum = monthPlanDetails.NextMonthPlanMoneyNum
                    });
                }
            }
            else
            {
                YearPlanRevise yearPlanRevise = YearPlanReviseRepository.Entities.Where(yr => yr.ProjectID == projectID && yr.ContractType == contractType && yr.ContractID == contractID && yr.StatisticalCycle == year).OrderByDescending(yr => yr.ReviseDate).FirstOrDefault();
                if (yearPlanRevise != null)
                {
                    IQueryable<YearPlanReviseDetails> lstYearPlanReviseDetail = YearPlanReviseDetailsRepository.Entities.Where(yrd => yrd.YearPlanReviseID == yearPlanRevise.ID);
                    foreach (YearPlanReviseDetails yearPlanReviseDetails in lstYearPlanReviseDetail)
                    {
                        switch (month)
                        {
                            case "1":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.JanuaryEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.JanuaryMoneyNum
                                });
                                break;
                            case "2":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.FebruaryEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.FebruaryMoneyNum
                                });
                                break;
                            case "3":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.MarchEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.MarchMoneyNum
                                });
                                break;
                            case "4":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.AprilEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.AprilMoneyNum
                                });
                                break;
                            case "5":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.MayEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.MayMoneyNum
                                });
                                break;
                            case "6":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.JuneEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.JuneMoneyNum
                                });
                                break;
                            case "7":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.JulyEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.JulyMoneyNum
                                });
                                break;
                            case "8":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.AugustEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.AugustMoneyNum
                                });
                                break;
                            case "9":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.SeptemberEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.SeptemberMoneyNum
                                });
                                break;
                            case "10":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.OctoberEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.OctoberMoneyNum
                                });
                                break;
                            case "11":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.NovemberEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.NovemberMoneyNum
                                });
                                break;
                            case "12":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.DecemberEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.DecemberMoneyNum
                                });
                                break;
                        }
                    }
                }
            }
            return lstLastMonthDetail;
        }

        //获取父统计项的名称
        private string GetParentStatisticsItemName(Guid? PID)
        {
            string parentStatisticsItemName = string.Empty;
            StatisticsItemMaintenance parentStatisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.SingleOrDefault(s => s.ID == PID);
            if (parentStatisticsItemMaintenance != null)
            {
                parentStatisticsItemName = parentStatisticsItemMaintenance.StatisticsItemName;
            }
            return parentStatisticsItemName;
        }

        private string SetStatisticalCycleNum(string statisticalCycle)
        {
            string statisticalCycleNum = "1";
            if (statisticalCycle == "中旬")
            {
                statisticalCycleNum = "2";
            }
            else if (statisticalCycle == "下旬")
            {
                statisticalCycleNum = "3";
            }
            return statisticalCycleNum;
        }
        #endregion

        #region 保存
        public void SaveStageSchedule(StageScheduleView stageScheduleView, List<StageScheduleDetailsView> saveList, bool isUpdateDetails = true)
        {
            StageSchedule record = StageScheduleRepository.Entities.FirstOrDefault(a => a.ID == stageScheduleView.ID);
            if (record != null)
            {
                UpdateStageSchedule(record, stageScheduleView);
            }
            else
            {
                InsertStageSchedule(stageScheduleView);
            }

            if (isUpdateDetails)
            {
                DeleteStageScheduleDetails(stageScheduleView.ID);
                foreach (StageScheduleDetailsView stageScheduleDetailsView in saveList)
                {
                    InsertStageScheduleDetails(stageScheduleDetailsView);
                }
            }
        }

        private void InsertStageSchedule(StageScheduleView stageScheduleView)
        {
            StageSchedule record = new StageSchedule()
            {
                ID = stageScheduleView.ID,
                FlowCode = stageScheduleView.FlowCode,
                ProjectID = stageScheduleView.ProjectID,
                ContractType = stageScheduleView.ContractType,
                ContractID = stageScheduleView.ContractID,
                Year = stageScheduleView.Year,
                Month = stageScheduleView.Month,
                StatisticalCycle = stageScheduleView.StatisticalCycle,
                StatisticalCycleNum = SetStatisticalCycleNum(stageScheduleView.StatisticalCycle),
                Unit = stageScheduleView.Unit,
                TotalStageCompletedMoneyNum = stageScheduleView.TotalStageCompletedMoneyNum,
                RequestDate = stageScheduleView.RequestDate,
                RequestPerson = stageScheduleView.RequestPerson,
                HandleState = stageScheduleView.HandleState,
                AssociatedNodeCode = stageScheduleView.AssociatedNodeCode,
                LastUpdateUserDepartment = stageScheduleView.LastUpdateUserDepartment,
                LastUpdateUser = stageScheduleView.LastUpdateUser,
                LastUpdateTime = stageScheduleView.LastUpdateTime,
                SaveState = stageScheduleView.SaveState
            };
            StageScheduleRepository.Insert(record);
        }

        private void UpdateStageSchedule(StageSchedule record, StageScheduleView stageScheduleView)
        {
            record.StatisticalCycle = stageScheduleView.StatisticalCycle;
            record.StatisticalCycleNum = SetStatisticalCycleNum(stageScheduleView.StatisticalCycle);
            record.Unit = stageScheduleView.Unit;
            record.TotalStageCompletedMoneyNum = stageScheduleView.TotalStageCompletedMoneyNum;
            record.HandleState = stageScheduleView.HandleState;
            record.AssociatedNodeCode = stageScheduleView.AssociatedNodeCode;
            record.LastUpdateUserDepartment = stageScheduleView.LastUpdateUserDepartment;
            record.LastUpdateUser = stageScheduleView.LastUpdateUser;
            record.LastUpdateTime = stageScheduleView.LastUpdateTime;
            record.SaveState = stageScheduleView.SaveState;
            StageScheduleRepository.Update(record);
        }

        private void DeleteStageScheduleDetails(Guid stageScheduleID)
        {
            List<StageScheduleDetails> lstStageScheduleDetails = StageScheduleDetailsRepository.Entities.Where(a => a.StageScheduleID == stageScheduleID).ToList();
            foreach (StageScheduleDetails stageScheduleDetails in lstStageScheduleDetails)
            {
                StageScheduleDetailsRepository.Delete(stageScheduleDetails.ID);
            }
        }

        private void InsertStageScheduleDetails(StageScheduleDetailsView stageScheduleDetailsView)
        {
            StageScheduleDetails record = new StageScheduleDetails()
            {
                ID = stageScheduleDetailsView.ID,
                StageScheduleID = stageScheduleDetailsView.StageScheduleID,
                StatisticsItemID = stageScheduleDetailsView.StatisticsItemID,
                StageCompletedEngineeringNum = stageScheduleDetailsView.StageCompletedEngineeringNum,
                StageCompletedMoneyNum = stageScheduleDetailsView.StageCompletedMoneyNum
            };
            StageScheduleDetailsRepository.Insert(record);
        }
        #endregion

        public OperationResult Delete(Guid id)
        {
            try
            {
                StageSchedule record = StageScheduleRepository.Entities.SingleOrDefault(t => t.ID == id);
                if (record == null)
                    return new OperationResult(OperationResultType.QueryNull, "未找到指定的记录");
                if (record != null)
                {
                    StageScheduleRepository.Delete(record);
                }

                string sql = @"DELETE FROM StageScheduleDetails WHERE StageScheduleID='" + record.ID + "';" +
                              "DELETE FROM BaklogTasks WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM BaklogTaskTemps WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM CompleteFlowNodes WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM FlowGraphNodes WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM FlowProcessMessages WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM ProcessedTasks WHERE RecordID='" + record.ID + "';";
                StageScheduleRepository.ExeSqlCommon(sql);
                return new OperationResult(OperationResultType.Success, "删除成功", record);
            }
            catch (Exception ex)
            {
                return new OperationResult(OperationResultType.Error, "删除失败:" + ex.Message);
            }
        }

        #region 旬报表
        public List<StageReportView> GetStageReportView(string year, string month, string stage, string contractType)
        {
            List<StageReportView> lstStageReportView = new List<StageReportView>();
            var lststatisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.Where(s => s.IsParent == false);
            foreach (StatisticsItemMaintenance statisticsItemMaintenance in lststatisticsItemMaintenance)
            {
                ProjectInfo projectInfo = ProjectInfoRepository.Entities.SingleOrDefault(p => p.ID == statisticsItemMaintenance.ProjectID);
                if (projectInfo != null && !string.IsNullOrEmpty(projectInfo.ProjectName))
                {
                    string parentStatisticsItemName = statisticsItemMaintenance.StatisticsItemName;
                    int parentStatisticsItemNameOrderNum = statisticsItemMaintenance.OrderNo;
                    if (statisticsItemMaintenance.PID != null)
                    {
                        StatisticsItemMaintenance parentStatisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.SingleOrDefault(s => s.ID == statisticsItemMaintenance.PID);
                        if (parentStatisticsItemMaintenance != null)
                        {
                            parentStatisticsItemName = parentStatisticsItemMaintenance.StatisticsItemName;
                            parentStatisticsItemNameOrderNum = parentStatisticsItemMaintenance.OrderNo;
                        }
                    }

                    #region 设计工程量
                    string totalEngineeringNum = string.Empty;
                    var lstTotalRevise = TotalReviseRepository.Entities.Where(t => t.ProjectID == statisticsItemMaintenance.ProjectID && t.ContractType == contractType).OrderByDescending(t => t.ReviseDate);
                    if (lstTotalRevise != null)
                    {
                        foreach (TotalRevise totalRevise in lstTotalRevise)
                        {
                            TotalReviseDetails totalReviseDetails = TotalReviseDetailsRepository.Entities.SingleOrDefault(td => td.TotalReviseID == totalRevise.ID && td.StatisticsItemID == statisticsItemMaintenance.ID);
                            if (totalReviseDetails != null)
                            {
                                totalEngineeringNum = CountEngineeringOrMoneyNumForDetails(totalReviseDetails.EngineeringNum, totalEngineeringNum);
                            }
                        }
                        lstStageReportView.Add(new StageReportView() { ParentStatisticsItemName = parentStatisticsItemName, ParentStatisticsItemNameOrderNum = parentStatisticsItemNameOrderNum, StatisticsItemName = statisticsItemMaintenance.StatisticsItemName, StatisticsItemNameOrderNum = statisticsItemMaintenance.OrderNo, Unit = statisticsItemMaintenance.EngineeringUnit,ProjectID=statisticsItemMaintenance.ProjectID, ProjectName = projectInfo.ProjectName, ProjectNameOrderNum = projectInfo.OrderNo, ValueType = "设计工程量", ValueTypeOrderNum = 1, Value = totalEngineeringNum });
                    }
                    #endregion

                    #region 本期完成工程量
                    string currentStageEngineeringNum = string.Empty;
                    var lstStageSchedule = StageScheduleRepository.Entities.Where(ss => ss.ProjectID == statisticsItemMaintenance.ProjectID && ss.ContractType == contractType && ss.Year == year && ss.Month == month && ss.StatisticalCycle == stage && ss.HandleState == "2");
                    if (lstStageSchedule != null)
                    {
                        foreach (StageSchedule stageSchedule in lstStageSchedule)
                        {
                            StageScheduleDetails stageScheduleDetails = StageScheduleDetailsRepository.Entities.SingleOrDefault(td => td.StageScheduleID == stageSchedule.ID && td.StatisticsItemID == statisticsItemMaintenance.ID);
                            if (stageScheduleDetails != null)
                            {
                                currentStageEngineeringNum = CountEngineeringOrMoneyNumForDetails(stageScheduleDetails.StageCompletedEngineeringNum, currentStageEngineeringNum);
                            }
                        }
                        lstStageReportView.Add(new StageReportView() { ParentStatisticsItemName = parentStatisticsItemName, ParentStatisticsItemNameOrderNum = parentStatisticsItemNameOrderNum, StatisticsItemName = statisticsItemMaintenance.StatisticsItemName, StatisticsItemNameOrderNum = statisticsItemMaintenance.OrderNo, Unit = statisticsItemMaintenance.EngineeringUnit, ProjectID = statisticsItemMaintenance.ProjectID, ProjectName = projectInfo.ProjectName, ProjectNameOrderNum = projectInfo.OrderNo, ValueType = "本期完成工程量", ValueTypeOrderNum = 2, Value = currentStageEngineeringNum });
                    }
                    #endregion

                    #region 上期末累计完成工程量
                    string lastYear = string.Empty;
                    string lastMonth = string.Empty;
                    string lastStage = string.Empty;
                    SetLastYearMonthStage(year, month, stage, ref lastYear, ref lastMonth, ref lastStage);
                    string lastStageNum = SetStatisticalCycleNum(lastStage);

                    string lastStageEndTotalEngineeringNum = string.Empty;
                    var lstStageScheduleLast = StageScheduleRepository.Entities.Where(m => m.ProjectID == statisticsItemMaintenance.ProjectID && m.ContractType == contractType && ((m.Year.CompareTo(year) < 0) || (m.Year == year && m.Month.CompareTo(month) < 0) || (m.Year == year && m.Month == month && m.StatisticalCycleNum.CompareTo(lastStageNum) <= 0)) && m.HandleState == "2");
                    if (lstStageScheduleLast != null)
                    {
                        foreach (StageSchedule stageSchedule in lstStageScheduleLast)
                        {
                            StageScheduleDetails stageScheduleDetails = StageScheduleDetailsRepository.Entities.SingleOrDefault(td => td.StageScheduleID == stageSchedule.ID && td.StatisticsItemID == statisticsItemMaintenance.ID);
                            if (stageScheduleDetails != null)
                            {
                                lastStageEndTotalEngineeringNum = CountEngineeringOrMoneyNumForDetails(stageScheduleDetails.StageCompletedEngineeringNum, lastStageEndTotalEngineeringNum);
                            }
                        }
                        lstStageReportView.Add(new StageReportView() { ParentStatisticsItemName = parentStatisticsItemName, ParentStatisticsItemNameOrderNum = parentStatisticsItemNameOrderNum, StatisticsItemName = statisticsItemMaintenance.StatisticsItemName, StatisticsItemNameOrderNum = statisticsItemMaintenance.OrderNo, Unit = statisticsItemMaintenance.EngineeringUnit, ProjectID = statisticsItemMaintenance.ProjectID, ProjectName = projectInfo.ProjectName, ProjectNameOrderNum = projectInfo.OrderNo, ValueType = "上期末累计完成工程量", ValueTypeOrderNum = 3, Value = lastStageEndTotalEngineeringNum });

                    }
                    #endregion

                    #region 开工累计完成工程量和累计完成工程量百分比
                    string constructionTotalEngineeringNum = CountEngineeringOrMoneyNumForDetails(currentStageEngineeringNum, lastStageEndTotalEngineeringNum);
                    lstStageReportView.Add(new StageReportView() { ParentStatisticsItemName = parentStatisticsItemName, ParentStatisticsItemNameOrderNum = parentStatisticsItemNameOrderNum, StatisticsItemName = statisticsItemMaintenance.StatisticsItemName, StatisticsItemNameOrderNum = statisticsItemMaintenance.OrderNo, Unit = statisticsItemMaintenance.EngineeringUnit, ProjectID = statisticsItemMaintenance.ProjectID, ProjectName = projectInfo.ProjectName, ProjectNameOrderNum = projectInfo.OrderNo, ValueType = "开工累计完成工程量", ValueTypeOrderNum = 4, Value = constructionTotalEngineeringNum });

                    string constructionCompletedTotalProportion = CountProportion(constructionTotalEngineeringNum, totalEngineeringNum, 2);
                    lstStageReportView.Add(new StageReportView() { ParentStatisticsItemName = parentStatisticsItemName, ParentStatisticsItemNameOrderNum = parentStatisticsItemNameOrderNum, StatisticsItemName = statisticsItemMaintenance.StatisticsItemName, StatisticsItemNameOrderNum = statisticsItemMaintenance.OrderNo, Unit = statisticsItemMaintenance.EngineeringUnit, ProjectID = statisticsItemMaintenance.ProjectID, ProjectName = projectInfo.ProjectName, ProjectNameOrderNum = projectInfo.OrderNo, ValueType = "累计完成工程量百分比", ValueTypeOrderNum = 5, Value = constructionCompletedTotalProportion });
                    #endregion
                }
            }

            if (lstStageReportView.Count > 0)
            {
                Guid projectID = lstStageReportView[0].ProjectID;
                var lstStageReportViewForProjectID = lstStageReportView.Where(s => s.ProjectID == projectID);
                foreach (StageReportView stageReportView in lstStageReportViewForProjectID)
                {
                    var lst = lstStageReportView.Where(sr => sr.ParentStatisticsItemName == stageReportView.ParentStatisticsItemName && sr.StatisticsItemName == stageReportView.StatisticsItemName);
                    foreach (StageReportView item in lst)
                    {
                        item.ParentStatisticsItemNameOrderNum = stageReportView.ParentStatisticsItemNameOrderNum;
                        item.StatisticsItemNameOrderNum = stageReportView.StatisticsItemNameOrderNum;
                    }
                }
            }
            //DataTable dt = new DataTable();
            //dt.Columns.Add("ParentStatisticsItemName");
            //dt.Columns.Add("ParentStatisticsItemNameOrderNum");
            //dt.Columns.Add("StatisticsItemName");
            //dt.Columns.Add("StatisticsItemNameOrderNum");
            //dt.Columns.Add("Unit");
            //dt.Columns.Add("ProjectID");
            //dt.Columns.Add("ProjectName");
            //dt.Columns.Add("ProjectNameOrderNum");
            //dt.Columns.Add("ValueType");
            //dt.Columns.Add("ValueTypeOrderNum");

            //lstStageReportView = lstStageReportView.OrderBy(l => l.ParentStatisticsItemName).ThenBy(l => l.StatisticsItemName).ToList();
            //foreach (StageReportView item in lstStageReportView)
            //{
            //    DataRow dr = dt.NewRow();
            //    dr["ParentStatisticsItemName"] = item.ParentStatisticsItemName;
            //    dr["ParentStatisticsItemNameOrderNum"] = item.ParentStatisticsItemNameOrderNum;
            //    dr["StatisticsItemName"] = item.StatisticsItemName;
            //    dr["StatisticsItemNameOrderNum"] = item.StatisticsItemNameOrderNum;
            //    dr["Unit"] = item.Unit;
            //    dr["ProjectID"] = item.ProjectID;
            //    dr["ProjectName"] = item.ProjectName;
            //    dr["ProjectNameOrderNum"] = item.ProjectNameOrderNum;
            //    dr["ValueType"] = item.ValueType;
            //    dr["ValueTypeOrderNum"] = item.ValueTypeOrderNum;
            //    dt.Rows.Add(dr);
            //}
            return lstStageReportView;
        }

        //设置当前年月旬的上一个旬
        private void SetLastYearMonthStage(string year, string month, string stage, ref string lastYear, ref string lastMonth, ref string lastStage)
        {
            if (!string.IsNullOrEmpty(year) && !string.IsNullOrEmpty(month) && !string.IsNullOrEmpty(stage))
            {
                lastYear = year;
                lastMonth = month;
                if (stage == "上旬")
                {
                    int monthNum = Convert.ToInt32(month);
                    if (monthNum == 1)
                    {
                        lastYear = (Convert.ToInt32(year) - 1).ToString();
                        lastMonth = "12";
                    }
                    else
                    {
                        lastMonth = (monthNum - 1).ToString();
                    }
                    lastStage = "下旬";
                }
                else if (stage == "中旬")
                {
                    lastStage = "上旬";
                }
                else
                {
                    lastStage = "中旬";
                }
            }
        }
        #endregion
    }
}